<script setup lang="ts">
const valid = defineModel('valid')
const isIdle = defineModel('isIdle', { type: Boolean, default: true })

// 通过验证且倒计时没开始，或者倒计时结束
const canSend = computed(() => {
  return isIdle.value && valid.value
})

const { count, dec, reset } = useCounter(1, { min: 1, max: 59 })

const { pause, resume } = useInterval(1000, { controls: true, callback: () => {
  if (count.value === 1) {
    isIdle.value = true
    pause()
  }
  else {
    isIdle.value = false
    dec()
  }
} })
const text = computed(() => {
  return isIdle.value ? '获取验证码' : `获取中(${count.value}s)`
})
pause()

function start() {
  if (isIdle.value) {
    resume()
    reset()
    isIdle.value = false
  }
}
watch(isIdle, (newVal) => {
  if (newVal) {
    reset()
    pause()
  }
})
</script>

<template>
  <el-button :disabled="!canSend" class="ml-2 w-30" @click="start">
    {{ text }}
  </el-button>
</template>
